package com.example.petshop.controller;

import com.example.petshop.entity.User;
import com.example.petshop.service.UserService;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;
    @Autowired
    private UserService userService;

    // 获取验证码接口
    @GetMapping("/captcha")
    public String getCaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        byte[] captchaChallengeAsJpeg;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            // 生成验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            httpServletRequest.getSession().setAttribute("vrifyCode", createText);
            // 使用生成的验证码字符串返回一个BufferedImage对象并转为byte数组
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return "Internal Error";
        }

        // 对字节数组Base64编码
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        String captchaBase64 = Base64.getEncoder().encodeToString(captchaChallengeAsJpeg);

        // 将Base64编码的验证码图片返回
        return "data:image/jpeg;base64," + captchaBase64;
    }

    // 登录接口
    @PostMapping("/login")
    public ResponseEntity<User> login(@RequestBody User user, HttpServletRequest request) {
        System.out.println("Received login request with username: " + user.getUsername());
        System.out.println("Received password: " + user.getPassword());
        System.out.println("Received code: " + user.getCode());

        HttpSession session = request.getSession();

        if (user.getCode() != null && !user.getCode().isEmpty()) {
            String sessionCaptcha = (String) session.getAttribute("vrifyCode");
            if (!user.getCode().equalsIgnoreCase(sessionCaptcha)) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
            }
        }

        boolean loggedIn = userService.login(user.getUsername(), user.getPassword());
        if (loggedIn) {
            // 登录成功，获取用户信息包括昵称
            User loggedInUser = userService.getUserByUsername(user.getUsername());
            System.out.println("Logged in user from database: " + loggedInUser);

            if (loggedInUser != null) {
                // 将用户信息存储到Session中
                session.setAttribute("loggedInUser", loggedInUser);
                System.out.println("Session ID in /login: " + session.getId());
                return ResponseEntity.ok(loggedInUser);
            } else {
                return ResponseEntity.notFound().build();
            }
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
    }


    @PostMapping("/register")
    @ResponseBody
    public boolean register(@RequestBody User user, HttpServletRequest request, HttpServletResponse response) {
        return userService.register(user);
    }

    @GetMapping("/profile")
    public User getUserProfile() {
        return userService.getUserProfile();
    }

    @GetMapping("/all")
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    @GetMapping("/getnickname")
    public String getNickname(HttpServletRequest request) {
        HttpSession session = request.getSession(true);
        System.out.println("session" + session);
        System.out.println("session Id" + session.getId());
        if (session != null) {
            User loggedInUser = (User) session.getAttribute("loggedInUser");

            if (loggedInUser != null) {
                System.out.println("Session ID in /getnickname: " + session.getId());
                return loggedInUser.getNickName();
            }
        }
        System.out.println("1111111111");
        return "Unknown";
    }

    @GetMapping("/getuserinfo")
    public ResponseEntity<User> getUserInfo(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            User loggedInUser = (User) session.getAttribute("loggedInUser");
            if (loggedInUser != null) {
                System.out.println("Session ID in /getuserinfo: " + session.getId());
                System.out.println("Retrieved user info: " + loggedInUser); // 打印用户信息用于调试
                // 确保性别属性始终存在
                if (loggedInUser.getSex() == null) {
                    loggedInUser.setSex("");
                }
                return ResponseEntity.ok(loggedInUser);
            } else {
                return ResponseEntity.notFound().build();
            }
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
    }

    @GetMapping("/getavatar")
    public ResponseEntity<String> getAvatar(HttpSession session) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");

        if (loggedInUser != null) {
            String avatar = loggedInUser.getAvatar();
            System.out.println("avatar:  " + avatar);
            return ResponseEntity.ok(avatar);
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
    }
    @GetMapping("/avatarByNickname")
    public ResponseEntity<String> getAvatarByNickname(@RequestParam("nickname") String nickname) {
        User user = userService.getUserByNickname(nickname);
        if (user != null) {
            return ResponseEntity.ok(user.getAvatar());
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    @GetMapping("/getusertype")
    public String getuserType(HttpServletRequest request) {
        HttpSession session = request.getSession(true);
        System.out.println("session" + session);
        System.out.println("session Id" + session.getId());
        if (session != null) {
            User loggedInUser = (User) session.getAttribute("loggedInUser");

            if (loggedInUser != null) {
                System.out.println("Session ID in /getnickname: " + session.getId());
                return loggedInUser.getUserType();
            }
        }
        System.out.println("1111111111");
        return "Unknown";
    }

    @PostMapping("/updateusertype")
    public ResponseEntity<?> updateuserType(@RequestBody User userType, HttpSession session) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        System.out.println("asdasd" + userType);
        if (loggedInUser != null) {
            boolean updated = userService.updateUserType(loggedInUser.getUserId(), userType.getUserType());
            if (updated) {
                return ResponseEntity.ok("用户类型更新成功");
            } else {
                return ResponseEntity.badRequest().body("用户类型更新失败");
            }
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
    }

    @GetMapping("/details/{userId}")
    public User getUserDetails(@PathVariable Integer userId) {
        return userService.getUserById(userId);
    }

    @GetMapping("/getall")
    public List<User> getAllUser() {
        return userService.getAllUser();
    }

    @PostMapping("/create")
    public ResponseEntity<Void> createUser(@RequestBody User user) {
        System.out.println(user);
        userService.createUser(user);
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/delete/{userId}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long userId) {
        userService.deleteUser(userId);
        return ResponseEntity.ok().build();
    }

    @PutMapping("/update")
    public ResponseEntity<Void> updateUser(@RequestBody User user) {
        userService.updateUser(user);
        return ResponseEntity.ok().build();
    }
}
